//
//  OAuthViewController.swift
//  WEIBO
//
//  Created by 李龙 on 15/6/25.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController,UIWebViewDelegate {

    private let Wb_client_ID = "1678239701"
    private let wb_Redict_uro = "http://www.baidu.com"
    private let wb_Redict_uros = "https://www.baidu.com"
    private let client_secret = "1a247642c9277c30590b5244ddc09453"
    var webView: UIWebView?
    override func viewDidLoad() {
        super.viewDidLoad()
        loadAutoPage()
        // Do any additional setup after loading the view.
    }
    override func loadView() {
       super.loadView()
        webView = UIWebView()
        webView?.delegate = self
        view = webView
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    private func loadAutoPage()
    {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(Wb_client_ID)&redirect_uri=\(wb_Redict_uro)"
        let url = NSURL(string: urlString)!
        webView?.loadRequest(NSURLRequest(URL: url))
    }
    func close()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print(urlString)
        if !urlString.hasPrefix(wb_Redict_uro){
            return true
        }
        print("需要判断")
        let querry = request.URL!.query!
        let codeStr = "code="
        if querry.hasPrefix(codeStr)
        {
            let code = querry.substringFromIndex(advance(codeStr.endIndex, 0))
            print("获取授权码\(code)")
            loadAccessToken(code)
        }
        else
        {
            print("验证失败")
            close()
        }
       // print("222")
        return false
    }
    private func loadAccessToken(code :String)
    {
        let urlString = "oauth2/access_token"
        let params = ["client_id": Wb_client_ID,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": wb_Redict_uro]
//        let a = account(dict: ["a":"b"])
//        a.loadUserInfo { (userAccount, error) -> () in
//            <#code#>
//        }
        //让返回的JSON的没有被反序列化的二进制数据 ---设置响应格式
      //  NetWebWorking.sharedNetWorkingTools().responseSerializer = AFHTTPResponseSerializer()
        NetWebWorking.sharedNetWorkingTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
           // print("----------")
           // let str = NSString(data: JSON as! NSData, encoding: NSUTF8StringEncoding)
          //  print(str)
            let UserAccount = account(dict: JSON as! [String : AnyObject])
            //UserAccount.saveAccount()
            UserAccount.loadUserInfo { (userAccount, error) -> () in
                if userAccount != nil
                {
                    shareAccount = userAccount
                    NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootVCNotification, object: false)
                    self.close()
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            print(UserAccount)
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
    }
    func webViewDidStartLoad(webView: UIWebView) {
        print("正在玩命加载。。。")
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        print("正在玩命退出。。。")
        SVProgressHUD.dismiss()
    }
}
